package com.atguigu.security.config;

import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Objects;

/**
 * @Description: 加密service
 * @Author: zhoufuzong
 * @Created: 2020-12-13 14:22:50
 * @Version: 1.1.0
 */

@Component
public class MyPasswordEncoderService  implements PasswordEncoder {


    @Override
    public String encode(CharSequence rawPassword) {
        return privateEndcode(rawPassword);
    }

    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword ) {

        // 1. 对明文密码进行加密
        String fromPassword = privateEndcode(rawPassword);

        //2. 数据库密码
        String  dataBasePassword = encodedPassword;

        return Objects.equals(fromPassword,encodedPassword);


    }

    private  String privateEndcode(CharSequence rawPassword){
        try {
            // 1. 创建messageDigest对象

            String algorithm = "MD5";
            MessageDigest messageDigest = MessageDigest.getInstance(algorithm);

            //2.获取rawPassword的字节数组
            byte[] input =String.valueOf(rawPassword).getBytes();

            // 3. 加密
            byte[] output = messageDigest.digest(input);

            // 4. 转换为16进制数对应字符
            String encode = new BigInteger(1,output).toString(16).toUpperCase();
            return encode;

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) {

        String privateEndcode = new MyPasswordEncoderService().privateEndcode("123123");
        System.out.println(privateEndcode);

    }
}
